<template>
  <div class="individual-configuration p-4">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="success" @click="deBounceWrap(handleAdd)"
          >新增</el-button
        >
        <el-button type="danger" @click="deBounceWrap(handleDelAll)"
          >批量删除</el-button
        >
        <el-button type="success" @click="deBounceWrap(handleEditAll)"
          >一键修改</el-button
        >
        <div>
          <el-row :gutter="20">
            <el-col :span="6" :offset="6">
              <el-button
                :type="currentBoxType === 7 ? 'primary' : ''"
                @click="handleChangePoolIndex(7)"
                style="background: #cc9933; color: #fff"
                >铜盲盒</el-button
              >
              <el-button
                :type="currentBoxType === 8 ? 'primary' : ''"
                @click="handleChangePoolIndex(8)"
                style="background: #c0c0c0; color: #fff"
                >银盲盒</el-button
              >
              <el-button
                :type="currentBoxType === 9 ? 'primary' : ''"
                @click="handleChangePoolIndex(9)"
                style="background: #ffd700; color: #fff"
                >金盲盒</el-button
              ></el-col
            >
          </el-row>
        </div>
        <el-row :gutter="20" class="mt-4">
          <el-col :span="12" :offset="6">
            <div></div>
            <div>
              <el-button
                v-for="(btnNum, index) in poolList"
                :key="btnNum"
                :type="currentPoolIndex === btnNum ? 'primary' : ''"
                @click="handleChangePoolIndex(btnNum)"
                >{{ "奖池" + (index + 1) }}</el-button
              >
            </div>
          </el-col>
        </el-row>
      </div>
      <el-table
        :data="tableData"
        border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="gift_name" label="名称"> </el-table-column>
        <el-table-column prop="price" label="价格"></el-table-column>
        <el-table-column prop="picture" label="图片">
          <template slot-scope="scope">
            <el-popover placement="right" width="220" trigger="hover">
              <img :src="scope.row.picture" alt="" style="max-width: 200px" />
              <img
                slot="reference"
                :src="scope.row.picture"
                alt=""
                style="width: 100px"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              plain
              @click="deBounceWrap(handleEdit, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              plain
              @click="deBounceWrap(handleDel, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- <cus-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.per_page"
        @pagination="getList"
      /> -->
    </el-card>
    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="titleOptions[title] + '礼物'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      @close="handleClear"
      width="30%"
      :before-close="handleClose"
    >
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item label="选择礼物" prop="gift_id" label-width="120px">
          <el-select v-model="form.gift_id">
            <el-option
              v-for="item in giftlistOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="num" label-width="120px">
          <el-input v-model.number="form.num" clearable></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" plain @click="handleClose">返回</el-button>
        <el-button type="primary" @click="deBounceWrap(handleSumbit, 'form')"
          >提交</el-button
        >
      </div>
    </el-dialog>
    <!-- 一键修改 -->
    <el-dialog
      v-dialogDrag
      title="一键修改"
      :visible.sync="dialogFormVisible2"
      @close="handleDialogClose2"
    >
      <el-form
        ref="form2"
        :model="form2"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <template v-for="(item, index) in form2Arr">
          <el-form-item
            label="选择礼物"
            :rules="{
              required: true,
              message: '礼物不能为空',
              trigger: 'change'
            }"
          >
            <el-select v-model="item.gift_id">
              <el-option
                v-for="item in giftlistOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="数量"
            :prop="'form2Arr.' + index + '.num'"
            :rules="{
              required: true,
              message: '数量不能为空',
              trigger: 'blur'
            }"
          >
            <el-input v-model="item.quantity" placeholder="请输入数量" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" plain @click="handleClose2">返回</el-button>
        <el-button type="primary" @click="deBounceWrap(handleSumbit2, 'form')"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  pondType,
  pondSet,
  boxgiftAdd,
  boxgiftEdit,
  boxgiftDel
} from "../../api/blindBox/individualConfiguration";
import { giftlist } from "@/api/blindBox";
export default {
  name: "individualConfiguration",
  data() {
    return {
      /*
       * 当前盲盒类型
       *    7 : 铜盲盒
       *    8 : 银盲盒
       *    9 : 金盲盒
       *  */
      currentBoxType: 7,
      /*
       * 当前奖池值
       * */
      currentPoolIndex: 10,
      /* 奖池按钮列表 */
      poolList: [],
      /* table 数据 */
      tableData: [],
      //每行
      rowData: {},
      //礼物列表
      giftlistOptions: [],
      titleOptions: {
        add: "新增",
        edit: "编辑"
      },
      title: "add",
      //表单
      form: {
        pond_type: undefined,
        box_type: undefined,
        gift_id: undefined,
        num: undefined,
        gift_info: undefined
      },
      //新增/编辑弹窗
      dialogVisible: false,
      rules: {
        gift_id: [{ required: true, message: "请选择礼物", trigger: "change" }],
        num: [{ required: true, message: "请输入初始数量", trigger: "blur" }]
      },
      //勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: "",
      //一键删除
      dialogFormVisible2: false,
      form2: {
        pond_type: undefined,
        box_type: undefined,
        gift_id: undefined,
        num: undefined,
        gift_info: undefined
      },
      form2Arr: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /* 点击切换当前状态 */
    handleChangePoolIndex(value) {
      if (value <= 9) {
        this.currentBoxType = value;
      } else {
        this.currentPoolIndex = value;
      }
    },
    /* 获取列表 */
    getList() {
      pondSet(this.currentPoolIndex)
        .then(({ data: { list, num_total, price_total } }) => {
          this.tableData = list;
          this.form2Arr = list;
        })
        .catch(console.error);
    },
    //获取礼物列表
    getGiftList() {
      giftlist(this.form.pond_type).then(res => {
        this.giftlistOptions = res.data;
      });
    },
    //新增
    async handleAdd() {
      this.title = "add";
      if (this.giftlistOptions.length === 0) {
        await this.getGiftList();
      }
      this.dialogVisible = true;
    },
    //编辑
    async handleEdit(row) {
      this.title = "edit";
      this.rowData = row;
      await this.getGiftList();
;
      this.form.gift_id = this.rowData.gift_id;
      this.form.num = this.rowData.quantity;
      this.dialogVisible = true;
    },
    //提交
    handleSumbit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title === "add") {
            let data = {
              box_type: this.currentBoxType,
              pond_type: this.currentPoolIndex,
              gift_id: this.form.gift_id,
              num: this.form.num
            };
            boxgiftAdd(data).then(res => {
              if (res.code === 200) {
                this.$message.success("操作成功");
                this.getList();
                this.dialogVisible = false;
              }
            });
          } else {
          }
          if (this.title === "edit") {
            let gift_info = `${this.rowData.id},${this.form.gift_id},${this.form.num}`;
            boxgiftEdit({ pond_type: this.currentPoolIndex, gift_info }).then(
              res => {
                if (res.code === 200) {
                  this.$message.success("编辑成功");
                  this.getList();
                  this.dialogVisible = false;
                }
              }
            );
          }
        } else {
          return false;
        }
      });
    },
    //弹窗框的清除关闭
    handleClose() {
      this.dialogVisible = false;
    },
    handleClear() {
      this.$refs["form"].resetFields();
      this.form = {
        pond_type: undefined,
        box_type: undefined,
        gift_id: undefined,
        num: undefined,
        gift_info: undefined
      };
    },
    //删除
    handleDel(row) {
      this.$confirm("确认删除!?此步骤无法恢复", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = { ids: row.id };
          boxgiftDel(data).then(res => {
            if (res.code === 200) {
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //批量删除
    handleDelAll() {
      if (this.multipleSelection.length) {
        /* 存在勾选数据 */ const ids = this.multipleSelection.reduce(
          (pre, currRow) => {
            pre += `${currRow.id},`;
            return pre;
          },
          ""
        );
        boxgiftDel({ ids })
          .then(() => this.$message.success("删除成功！"))
          .catch(console.error)
          .finally(() => /* 刷新数据 */ {
            this.multipleSelection = [];
            this.getList();
          });
      } /* 不存在勾选数据 */ else {
        this.$message.warning("请勾选要删除的数据！");
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //一键修改
    handleEditAll() {
      this.dialogFormVisible2 = true;
      this.getGiftList();
    },
    //一键删除提交
    handleSumbit2() {
      let gift_info = this.form2Arr.reduce((pre, curr) => {
        pre += `${curr.id},${curr.gift_id},${curr.quantity};`;
        return pre;
      }, "");
      boxgiftEdit({ pond_type: this.currentPoolIndex, gift_info }).then(res => {
        if (res.code === 200) {
          this.$message.success("编辑成功");
          this.getList();
          this.dialogFormVisible2 = false;
        }
      });
    },
    //
    handleClose2() {
      this.dialogFormVisible2 = false;
    },
    handleDialogClose2() {
      this.$refs["form2"].resetFields();
      this.form2 = {
        pond_type: undefined,
        box_type: undefined,
        gift_id: undefined,
        num: undefined,
        gift_info: undefined
      };
    }
  },
  watch: {
    currentPoolIndex: {
      immediate: true,
      handler(value) {
        this.getList();
      }
    },
    currentBoxType: {
      immediate: true,
      handler(value) {
        pondType(this.currentBoxType)
          .then(({ data }) => {
            this.poolList = data;
            this.currentPoolIndex = this.poolList[0];
          })
          .catch(console.error);
      }
    }
  }
};
</script>
